#!/usr/bin/perl -w

use POSIX;
use Fcntl;
use Config::IniFiles;
use Data::Dumper;
use solv;
use Devel::Peek;
use FileHandle;
use File::Temp ();
use strict;

package Repo::generic;

sub new {
  my ($class, $alias, $type, $attr) = @_;
  my $r = { %{$attr || {}} };
  $r->{alias} = $alias;
  $r->{type} = $type;
  return bless $r, $class;
}

sub calc_cookie_fp {
  my ($self, $fp) = @_;
  my $chksum = solv::Chksum->new($solv::REPOKEY_TYPE_SHA256);
  $chksum->add("1.1");
  $chksum->add_fp($fp);
  return $chksum->raw();
}

sub calc_cookie_file {
  my ($self, $filename) = @_;
  my $chksum = solv::Chksum->new($solv::REPOKEY_TYPE_SHA256);
  $chksum->add("1.1");
  $chksum->add_stat($filename);
  return $chksum->raw();
}

sub calc_cookie_ext {
  my ($self, $f, $cookie) = @_;
  my $chksum = solv::Chksum->new($solv::REPOKEY_TYPE_SHA256);
  $chksum->add("1.1");
  $chksum->add($cookie);
  $chksum->add_fstat(fileno($f));
  return $chksum->raw();
}

sub cachepath {
  my ($self, $ext) = @_;
  my $path = $self->{alias};
  $path =~ s/^\./_/s;
  $path .= $ext ? "_$ext.solvx" : '.solv';
  $path =~ s!/!_!gs;
  return "/var/cache/solv/$path";
}

sub load {
  my ($self, $pool) = @_;
  $self->{handle} = $pool->add_repo($self->{alias});
  $self->{handle}->{appdata} = $self;
  $self->{handle}->{priority} = 99 - $self->{priority};
  my $dorefresh = $self->{autorefresh};
  if ($dorefresh) {
    my @s = stat($self->cachepath());
    $dorefresh = 0 if @s && ($self->{metadata_expire} == -1 || time() - $s[9] < $self->{metadata_expire});
  }
  $self->{cookie} = '';
  $self->{extcookie} = '';
  if (!$dorefresh && $self->usecachedrepo()) {
    print "repo: '$self->{alias}' cached\n";
    return 1;
  }
  return 0;
}

sub load_ext {
  return 0;
}

sub download {
  my ($self, $file, $uncompress, $chksum, $markincomplete) = @_;
  if (!$self->{baseurl}) {
    print "$self->{alias}: no baseurl\n";
    return undef;
  }
  my $url = $self->{baseurl};
  $url =~ s!/$!!;
  $url .= "/$file";
  open(my $f, '+>', undef) || die;
  fcntl($f, Fcntl::F_SETFD, 0);		# turn off CLOEXEC
  my $st = system('curl', '-f', '-s', '-L', '-o', "/dev/fd/" . fileno($f), '--', $url);
  if (POSIX::lseek(fileno($f), 0, POSIX::SEEK_END) == 0 && ($st == 0 || !$chksum)) {
    return undef;
  }
  POSIX::lseek(fileno($f), 0, POSIX::SEEK_SET);
  if ($st) {
    print "$file: download error #$st\n";
    $self->{incomplete} = 1 if $markincomplete;
    return undef;
  }
  if ($chksum) {
    my $fchksum = solv::Chksum->new($chksum->{type});
    $fchksum->add_fd(fileno($f));
    if ($fchksum != $chksum) {
      print "$file: checksum error\n";
      $self->{incomplete} = 1 if $markincomplete;
      return undef;
    }
  }
  if ($uncompress) {
    return solv::xfopen_fd($file, fileno($f));
  } else {
    return solv::xfopen_fd(undef, fileno($f));
  }
}

sub usecachedrepo {
  my ($self, $ext, $mark) = @_;
  my $cookie = $ext ? $self->{extcookie} : $self->{cookie};
  my $cachepath = $self->cachepath($ext);
  my $fextcookie;
  if (sysopen(my $f, $cachepath, POSIX::O_RDONLY)) {
    sysseek($f, -32, Fcntl::SEEK_END);
    my $fcookie = '';
    return undef if sysread($f, $fcookie, 32) != 32;
    return undef if $cookie && $fcookie ne $cookie;
    if ($self->{type} ne 'system' && !$ext) {
      sysseek($f, -32 * 2, Fcntl::SEEK_END);
      return undef if sysread($f, $fextcookie, 32) != 32;
    }
    sysseek($f, 0, Fcntl::SEEK_SET);
    my $fd = solv::xfopen_fd(undef, fileno($f));
    my $flags = $ext ? $solv::Repo::REPO_USE_LOADING|$solv::Repo::REPO_EXTEND_SOLVABLES : 0;
    $flags |= $solv::Repo::REPO_LOCALPOOL if $ext && $ext ne 'DL';
    if (!$self->{handle}->add_solv($fd, $flags)) {
      return undef;
    }
    $self->{cookie} = $fcookie unless $ext;
    $self->{extcookie} = $fextcookie if $fextcookie;
    utime undef, undef, $f if $mark;
    return 1;
  }
  return undef;
}

sub writecachedrepo {
  my ($self, $ext, $repodata) = @_;
  return if $self->{incomplete};
  mkdir("/var/cache/solv", 0755) unless -d "/var/cache/solv";
  my ($f, $tmpname);
  eval {
    ($f, $tmpname) = File::Temp::tempfile(".newsolv-XXXXXX", 'DIR' => '/var/cache/solv');
  };
  return unless $f;
  chmod 0444, $f;
  my $ff = solv::xfopen_fd(undef, fileno($f));
  if (!$repodata) {
    $self->{handle}->write($ff);
  } elsif ($ext) {
    $repodata->write($ff);
  } else {
     $self->{handle}->write_first_repodata($ff);
  }
  undef $ff;	# also flushes
  if ($self->{type} ne 'system' && !$ext) {
    $self->{extcookie} ||= $self->calc_cookie_ext($f, $self->{cookie});
    syswrite($f, $self->{extcookie});
  }
  syswrite($f, $ext ? $self->{extcookie} : $self->{cookie});
  close($f);
  if ($self->{handle}->iscontiguous()) {
    $f = solv::xfopen($tmpname);
    if ($f) {
      if (!$ext) {
	$self->{handle}->empty();
	die("internal error, cannot reload solv file\n") unless $self->{handle}->add_solv($f, $repodata ? 0 : $solv::Repo::SOLV_ADD_NO_STUBS);
      } else {
	$repodata->extend_to_repo();
	my $flags = $solv::Repo::REPO_EXTEND_SOLVABLES;
	$flags |= $solv::Repo::REPO_LOCALPOOL if $ext ne 'DL';
	$repodata->add_solv($f, $flags);
      }
    }
  }
  rename($tmpname, $self->cachepath($ext));
}

sub packagespath {
  my ($self) = @_;
  return '';
}

my %langtags = (
  $solv::SOLVABLE_SUMMARY     => $solv::REPOKEY_TYPE_STR,
  $solv::SOLVABLE_DESCRIPTION => $solv::REPOKEY_TYPE_STR,
  $solv::SOLVABLE_EULA        => $solv::REPOKEY_TYPE_STR,
  $solv::SOLVABLE_MESSAGEINS  => $solv::REPOKEY_TYPE_STR,
  $solv::SOLVABLE_MESSAGEDEL  => $solv::REPOKEY_TYPE_STR,
  $solv::SOLVABLE_CATEGORY    => $solv::REPOKEY_TYPE_ID,
);

sub add_ext_keys {
  my ($self, $ext, $repodata, $handle) = @_;
  if ($ext eq 'DL') {
    $repodata->add_idarray($handle, $solv::REPOSITORY_KEYS, $solv::REPOSITORY_DELTAINFO);
    $repodata->add_idarray($handle, $solv::REPOSITORY_KEYS, $solv::REPOKEY_TYPE_FLEXARRAY);
  } elsif ($ext eq 'DU') {
    $repodata->add_idarray($handle, $solv::REPOSITORY_KEYS, $solv::SOLVABLE_DISKUSAGE);
    $repodata->add_idarray($handle, $solv::REPOSITORY_KEYS, $solv::REPOKEY_TYPE_DIRNUMNUMARRAY);
  } elsif ($ext eq 'FL') {
    $repodata->add_idarray($handle, $solv::REPOSITORY_KEYS, $solv::SOLVABLE_FILELIST);
    $repodata->add_idarray($handle, $solv::REPOSITORY_KEYS, $solv::REPOKEY_TYPE_DIRSTRARRAY);
  } else {
    for my $langid (sort { $a <=> $b } keys %langtags) {
      $repodata->add_idarray($handle, $solv::REPOSITORY_KEYS, $self->{handle}->{pool}->id2langid($langid, $ext, 1));
      $repodata->add_idarray($handle, $solv::REPOSITORY_KEYS, $langtags{$langid});
    }
  }
}

package Repo::rpmmd;

our @ISA = ('Repo::generic');

sub find {
  my ($self, $what) = @_;
  my $di = $self->{handle}->Dataiterator_meta($solv::REPOSITORY_REPOMD_TYPE, $what, $solv::Dataiterator::SEARCH_STRING);
  $di->prepend_keyname($solv::REPOSITORY_REPOMD);
  for my $d (@$di) {
    my $dp = $d->parentpos();
    my $filename = $dp->lookup_str($solv::REPOSITORY_REPOMD_LOCATION);
    next unless $filename;
    my $chksum = $dp->lookup_checksum($solv::REPOSITORY_REPOMD_CHECKSUM);
    if (!$chksum) {
      print "no $filename file checksum!\n";
      return (undef, undef);
    }
    return ($filename, $chksum);
  }
  return (undef, undef);
}

sub add_ext {
  my ($self, $repodata, $what, $ext) = @_;
  my ($filename, $chksum) = $self->find($what);
  ($filename, $chksum) = $self->find('prestodelta') if !$filename && $what eq 'deltainfo';
  return unless $filename;
  my $handle = $repodata->new_handle();
  $repodata->set_poolstr($handle, $solv::REPOSITORY_REPOMD_TYPE, $what);
  $repodata->set_str($handle, $solv::REPOSITORY_REPOMD_LOCATION, $filename);
  $repodata->set_checksum($handle, $solv::REPOSITORY_REPOMD_CHECKSUM, $chksum);
  $self->add_ext_keys($ext, $repodata, $handle);
  $repodata->add_flexarray($solv::SOLVID_META, $solv::REPOSITORY_EXTERNAL, $handle);
}

sub add_exts {
  my ($self) = @_;
  my $repodata = $self->{handle}->add_repodata(0);
  $repodata->extend_to_repo();
  $self->add_ext($repodata, 'deltainfo', 'DL');
  $self->add_ext($repodata, 'filelists', 'FL');
  $repodata->internalize();
}

sub load_ext {
  my ($self, $repodata) = @_;
  my $repomdtype = $repodata->lookup_str($solv::SOLVID_META, $solv::REPOSITORY_REPOMD_TYPE);
  my $ext;
  if ($repomdtype eq 'filelists') {
    $ext = 'FL';
  } elsif ($repomdtype eq 'deltainfo') {
    $ext = 'DL';
  } else {
    return 0;
  }
  print("[$self->{alias}:$ext: ");
  STDOUT->flush();
  if ($self->usecachedrepo($ext)) {
    print "cached]\n";
    return 1;
  }
  print "fetching]\n";
  my $filename = $repodata->lookup_str($solv::SOLVID_META, $solv::REPOSITORY_REPOMD_LOCATION);
  my $filechksum = $repodata->lookup_checksum($solv::SOLVID_META, $solv::REPOSITORY_REPOMD_CHECKSUM);
  my $f = $self->download($filename, 1, $filechksum);
  return 0 unless $f;
  if ($ext eq 'FL') {
    $self->{handle}->add_rpmmd($f, 'FL', $solv::Repo::REPO_USE_LOADING|$solv::Repo::REPO_EXTEND_SOLVABLES|$solv::Repo::REPO_LOCALPOOL);
  } elsif ($ext eq 'DL') {
    $self->{handle}->add_deltainfoxml($f, $solv::Repo::REPO_USE_LOADING);
  }
  $self->writecachedrepo($ext, $repodata);
  return 1;
}

sub load {
  my ($self, $pool) = @_;
  return 1 if $self->Repo::generic::load($pool);
  print "rpmmd repo '$self->{alias}': ";
  STDOUT->flush();
  my $f = $self->download("repodata/repomd.xml");
  if (!$f) {
    print "no repomd.xml file, skipped\n";
    $self->{handle}->free(1);
    delete $self->{handle};
    return undef;
  }
  $self->{cookie} = $self->calc_cookie_fp($f);
  if ($self->usecachedrepo(undef, 1)) {
    print "cached\n";
    return 1;
  }
  $self->{handle}->add_repomdxml($f, 0);
  print "fetching\n";
  my ($filename, $filechksum) = $self->find('primary');
  if ($filename) {
    $f = $self->download($filename, 1, $filechksum, 1);
    if ($f) {
      $self->{handle}->add_rpmmd($f, undef, 0);
    }
    return undef if $self->{incomplete};
  }
  ($filename, $filechksum) = $self->find('updateinfo');
  if ($filename) {
    $f = $self->download($filename, 1, $filechksum, 1);
    if ($f) {
      $self->{handle}->add_updateinfoxml($f, 0);
    }
  }
  $self->add_exts();
  $self->writecachedrepo();
  $self->{handle}->create_stubs();
  return 1;
}

package Repo::susetags;

our @ISA = ('Repo::generic');

sub find {
  my ($self, $what) = @_;
  
  my $di = $self->{handle}->Dataiterator_meta($solv::SUSETAGS_FILE_NAME, $what, $solv::Dataiterator::SEARCH_STRING);
  $di->prepend_keyname($solv::SUSETAGS_FILE);
  for my $d (@$di) {
    my $dp = $d->parentpos();
    my $chksum = $dp->lookup_checksum($solv::SUSETAGS_FILE_CHECKSUM);
    return ($what, $chksum);
  }
  return (undef, undef);
}


sub add_ext {
  my ($self, $repodata, $what, $ext) = @_;
  my ($filename, $chksum) = $self->find($what);
  return unless $filename;
  my $handle = $repodata->new_handle();
  $repodata->set_str($handle, $solv::SUSETAGS_FILE_NAME, $filename);
  $repodata->set_checksum($handle, $solv::SUSETAGS_FILE_CHECKSUM, $chksum);
  $self->add_ext_keys($ext, $repodata, $handle);
  $repodata->add_flexarray($solv::SOLVID_META, $solv::REPOSITORY_EXTERNAL, $handle);
}

sub add_exts {
  my ($self) = @_;
  my $repodata = $self->{handle}->add_repodata(0);
  my $di = $self->{handle}->Dataiterator_meta($solv::SUSETAGS_FILE_NAME, undef, 0);
  $di->prepend_keyname($solv::SUSETAGS_FILE);
  for my $d (@$di) {
    my $filename = $d->str();
    next unless $filename && $filename =~ /^packages\.(..)(?:\..*)$/;
    next if $1 eq 'en' || $1 eq 'gz';
    $self->add_ext($repodata, $filename, $1);
  }
  $repodata->internalize();
}

sub load_ext {
  my ($self, $repodata) = @_;
  my $filename = $repodata->lookup_str($solv::SOLVID_META, $solv::SUSETAGS_FILE_NAME);
  my $ext = substr($filename, 9, 2);
  print("[$self->{alias}:$ext: ");
  STDOUT->flush();
  if ($self->usecachedrepo($ext)) {
    print "cached]\n";
    return 1;
  }
  print "fetching]\n";
  my $defvendorid = $self->{handle}->{meta}->lookup_id($solv::SUSETAGS_DEFAULTVENDOR);
  my $descrdir = $self->{handle}->{meta}->lookup_str($solv::SUSETAGS_DESCRDIR) || 'suse/setup/descr'; 
  my $filechksum = $repodata->lookup_checksum($solv::SOLVID_META, $solv::SUSETAGS_FILE_CHECKSUM);
  my $f = $self->download("$descrdir/$filename", 1, $filechksum);
  return 0 unless $f;
  my $flags = $solv::Repo::REPO_USE_LOADING|$solv::Repo::REPO_EXTEND_SOLVABLES;
  $flags |= $solv::Repo::REPO_LOCALPOOL if $ext ne 'DL';
  $self->{handle}->add_susetags($f, $defvendorid, $ext, $flags);
  $self->writecachedrepo($ext, $repodata);
  return 1;
}

sub load {
  my ($self, $pool) = @_;
  return 1 if $self->Repo::generic::load($pool);
  print "susetags repo '$self->{alias}': ";
  STDOUT->flush();
  my $f = $self->download("content");
  if (!$f) {
    print "no content file, skipped\n";
    $self->{handle}->free(1);
    delete $self->{handle};
    return undef;
  }
  $self->{cookie} = $self->calc_cookie_fp($f);
  if ($self->usecachedrepo(undef, 1)) {
    print "cached\n";
    return 1;
  }
  $self->{handle}->add_content($f, 0);
  print "fetching\n";
  my $defvendorid = $self->{handle}->{meta}->lookup_id($solv::SUSETAGS_DEFAULTVENDOR);
  my $descrdir = $self->{handle}->{meta}->lookup_str($solv::SUSETAGS_DESCRDIR) || 'suse/setup/descr'; 
  my ($filename, $filechksum) = $self->find('packages.gz');
  ($filename, $filechksum) = $self->find('packages') unless $filename;
  if ($filename) {
    $f = $self->download("$descrdir/$filename", 1, $filechksum, 1);
    if ($f) {
      $self->{handle}->add_susetags($f, $defvendorid, undef, $solv::Repo::REPO_NO_INTERNALIZE|$solv::Repo::SUSETAGS_RECORD_SHARES);
      ($filename, $filechksum) = $self->find('packages.en.gz');
      ($filename, $filechksum) = $self->find('packages.en') unless $filename;
      if ($filename) {
	$f = $self->download("$descrdir/$filename", 1, $filechksum, 1);
	if ($f) {
	  $self->{handle}->add_susetags($f, $defvendorid, undef, $solv::Repo::REPO_NO_INTERNALIZE|$solv::Repo::REPO_REUSE_REPODATA|$solv::Repo::REPO_EXTEND_SOLVABLES);
	}
      }
      $self->{handle}->internalize();
    }
  }
  $self->add_exts();
  $self->writecachedrepo();
  $self->{handle}->create_stubs();
  return undef;
}

sub packagespath {
  my ($self) = @_;
  return ($self->{handle}->{meta}->lookup_str($solv::SUSETAGS_DATADIR) || 'suse') . '/';
}

package Repo::unknown;

our @ISA = ('Repo::generic');

sub load {
  my ($self) = @_;
  print "unsupported repo '$self->{alias}': skipped\n";
  return 0;
}

package Repo::system;

our @ISA = ('Repo::generic');

sub load {
  my ($self, $pool) = @_;

  $self->{handle} = $pool->add_repo($self->{alias});
  $self->{handle}->{appdata} = $self;
  $pool->{installed} = $self->{handle};
  print "rpm database: ";
  $self->{cookie} = $self->calc_cookie_file('/var/lib/rpm/Packages');
  if ($self->usecachedrepo()) {
    print "cached\n";
    return 1;
  }
  print "reading\n";
  if (defined(&solv::Repo::add_products)) {
    $self->{handle}->add_products("/etc/products.d", $solv::Repo::REPO_NO_INTERNALIZE);
  }
  my $f = solv::xfopen($self->cachepath());
  $self->{handle}->add_rpmdb_reffp($f, $solv::Repo::REPO_REUSE_REPODATA);
  $self->writecachedrepo();
  return 1;
}

package main;

sub load_stub {
  my ($repodata) = @_;
  my $repo = $repodata->{repo}->{appdata};
  return $repo ? $repo->load_ext($repodata) : 0;
}

die("Usage: p5solv COMMAND [ARGS]\n") unless @ARGV;
my $cmd = shift @ARGV;
my %cmdabbrev = ( 'ls' => 'list', 'in' => 'install', 'rm' => 'erase',
                  've' => 'verify', 'se' => 'search' );
$cmd = $cmdabbrev{$cmd} if $cmdabbrev{$cmd};

my %cmdactionmap = (
  'install' => $solv::Job::SOLVER_INSTALL,
  'erase'   => $solv::Job::SOLVER_ERASE,
  'up'      => $solv::Job::SOLVER_UPDATE,
  'dup'     => $solv::Job::SOLVER_DISTUPGRADE,
  'verify'  => $solv::Job::SOLVER_VERIFY,
  'list'    => 0,  
  'info'    => 0,
);

my @repos;
my @reposdirs;
if (-d '/etc/zypp/repos.d') {
  @reposdirs = ( '/etc/zypp/repos.d' );
} else {
  @reposdirs = ( '/etc/yum/repos.d' );
}
for my $reposdir (@reposdirs) {
  next unless -d $reposdir;
  my $dir;
  next unless opendir($dir, $reposdir);
  for my $reponame (sort(grep {/\.repo$/} readdir($dir))) {
    my $cfg = new Config::IniFiles('-file' => "$reposdir/$reponame");
    for my $alias ($cfg->Sections()) {
      my $repoattr = {'alias' => $alias, 'enabled' => 0, 'priority' => 99, 'autorefresh' => 1, 'type' => 'rpm-md', 'metadata_expire' => 900};
      for my $p ($cfg->Parameters($alias)) {
	$repoattr->{$p} = $cfg->val($alias, $p);
      }
      my $repo;
      if ($repoattr->{type} eq 'rpm-md') {
	$repo = Repo::rpmmd->new($alias, 'repomd', $repoattr);
      } elsif ($repoattr->{type} eq 'yast2') {
	$repo = Repo::susetags->new($alias, 'susetags', $repoattr);
      } else {
	$repo = Repo::unknown->new($alias, 'unknown', $repoattr);
      }
      push @repos, $repo;
    }
  }
}

my $pool = solv::Pool->new();
$pool->setarch();
$pool->set_loadcallback(\&load_stub);

my $sysrepo = Repo::system->new('@System', 'system');
$sysrepo->load($pool);
for my $repo (@repos) {
  $repo->load($pool) if $repo->{enabled};
}

if ($cmd eq 'search') {
  $pool->createwhatprovides();
  my $sel = $pool->Selection();
  my $di = $pool->Dataiterator($solv::SOLVABLE_NAME, $ARGV[0], $solv::Dataiterator::SEARCH_SUBSTRING | $solv::Dataiterator::SEARCH_NOCASE);
  for my $d (@$di) {
    $sel->add_raw($solv::Job::SOLVER_SOLVABLE, $d->{solvid});
  }
  for my $s ($sel->solvables()) {
    print "- ".$s->str()." [$s->{repo}->{name}]: ".$s->lookup_str($solv::SOLVABLE_SUMMARY)."\n";
  }
  exit(0);
}

die("unknown command '$cmd'\n") unless defined $cmdactionmap{$cmd};

$pool->addfileprovides();
$pool->createwhatprovides();
$pool->set_namespaceproviders($solv::NAMESPACE_LANGUAGE, $pool->Dep('de'), 1);

my @jobs;
for my $arg (@ARGV) {
  my $flags = $solv::Selection::SELECTION_NAME | $solv::Selection::SELECTION_PROVIDES | $solv::Selection::SELECTION_GLOB;
  $flags |= $solv::Selection::SELECTION_CANON | $solv::Selection::SELECTION_DOTARCH | $solv::Selection::SELECTION_REL;
  if ($arg =~ m!^/!) {
    $flags |= $solv::Selection::SELECTION_FILELIST;
    $flags |= $solv::Selection::SELECTION_INSTALLED_ONLY if $cmd eq 'erase';
  }
  my $sel = $pool->select($arg, $flags);
  if ($sel->isempty()) {
    $sel = $pool->select($arg, $flags | $solv::Selection::SELECTION_NOCASE);
    print "[ignoring case for '$arg']\n" unless $sel->isempty();
  }
  die("nothing matches '$arg'\n") if $sel->isempty();
  print "[using file list match for '$arg']\n" if $sel->{flags} & $solv::Selection::SELECTION_FILELIST;
  print "[using capability match for '$arg']\n" if $sel->{flags} & $solv::Selection::SELECTION_PROVIDES;
  push @jobs, $sel->jobs($cmdactionmap{$cmd});
}

if (!@jobs && ($cmd eq 'up' || $cmd eq 'dup' || $cmd eq 'verify')) {
  my $sel = $pool->Selection_all();
  push @jobs, $sel->jobs($cmdactionmap{$cmd});
}

die("no package matched.\n") unless @jobs;

if ($cmd eq 'list' || $cmd eq 'info') {
  for my $job (@jobs) {
    for my $s ($job->solvables()) {
      if ($cmd eq 'info') {
	printf "Name:        %s\n", $s->str();
	printf "Repo:        %s\n", $s->{repo}->{name};
	printf "Summary:     %s\n", $s->lookup_str($solv::SOLVABLE_SUMMARY);
	my $str = $s->lookup_str($solv::SOLVABLE_URL);
	printf "Url:         %s\n", $str if $str;
	$str = $s->lookup_str($solv::SOLVABLE_LICENSE);
	printf "License:     %s\n", $str if $str;
	printf "Description:\n%s\n", $s->lookup_str($solv::SOLVABLE_DESCRIPTION);
      } else {
	printf "  - %s [%s]\n", $s->str(), $s->{repo}->{name};
	printf "    %s\n", $s->lookup_str($solv::SOLVABLE_SUMMARY);
      }
    }
  }
  exit 0;
}

# up magic, turn into install if nothing matches
for my $job (@jobs) {
  $job->{how} ^= $solv::Job::SOLVER_UPDATE ^ $solv::Job::SOLVER_INSTALL if $cmd eq 'up' && $job->isemptyupdate();
}

my $solver = $pool->Solver();
$solver->set_flag($solv::Solver::SOLVER_FLAG_SPLITPROVIDES, 1);
$solver->set_flag($solv::Solver::SOLVER_FLAG_ALLOW_UNINSTALL, 1) if $cmd eq 'erase';

while (1) {
  my @problems = $solver->solve(\@jobs);
  last unless @problems;
  for my $problem (@problems) {
    print "Problem $problem->{id}/".@problems.":\n";
    print $problem->str()."\n";
    my @solutions = $problem->solutions();
    for my $solution (@solutions) {
      print "  Solution $solution->{id}:\n";
      for my $element ($solution->elements(1)) {
	print "  - ".$element->str()."\n";
      }
      print "\n";
    }
    my $sol;
    while (1) {
      print "Please choose a solution: ";
      $sol = <STDIN>;
      chomp $sol;
      last if $sol eq 's' || $sol eq 'q' || ($sol =~ /^\d+$/ && $sol >= 1 && $sol <= @solutions);
    }
    next if $sol eq 's';
    exit(1) if $sol eq 'q';
    my $solution = $solutions[$sol - 1];
    for my $element ($solution->elements()) {
      my $newjob = $element->Job();
      if ($element->{type} == $solv::Solver::SOLVER_SOLUTION_JOB) {
	$jobs[$element->{jobidx}] = $newjob;
      } else {
	push @jobs, $newjob if $newjob && !grep {$_ == $newjob} @jobs;
      }
    }
  }
}

my $trans = $solver->transaction();
undef $solver;
if ($trans->isempty()) {
  print "Nothing to do.\n";
  exit 0;
}

print "\nTransaction summary:\n\n";
for my $c ($trans->classify($solv::Transaction::SOLVER_TRANSACTION_SHOW_OBSOLETES|$solv::Transaction::SOLVER_TRANSACTION_OBSOLETE_IS_UPGRADE)) {
  if ($c->{type} == $solv::Transaction::SOLVER_TRANSACTION_ERASE) {
    print "$c->{count} erased packages:\n";
  } elsif ($c->{type} == $solv::Transaction::SOLVER_TRANSACTION_INSTALL) {
    print "$c->{count} installed packages:\n";
  } elsif ($c->{type} == $solv::Transaction::SOLVER_TRANSACTION_REINSTALLED) {
    print "$c->{count} reinstalled packages:\n";
  } elsif ($c->{type} == $solv::Transaction::SOLVER_TRANSACTION_DOWNGRADED) {
    print "$c->{count} downgraded packages:\n";
  } elsif ($c->{type} == $solv::Transaction::SOLVER_TRANSACTION_CHANGED) {
    print "$c->{count} changed packages:\n";
  } elsif ($c->{type} == $solv::Transaction::SOLVER_TRANSACTION_UPGRADED) {
    print "$c->{count} upgraded packages:\n";
  } elsif ($c->{type} == $solv::Transaction::SOLVER_TRANSACTION_VENDORCHANGE) {
    printf "$c->{count} vendor changes from '%s' to '%s':\n", $c->{fromstr}, $c->{tostr};
  } elsif ($c->{type} == $solv::Transaction::SOLVER_TRANSACTION_ARCHCHANGE) {
    printf "$c->{count} arch changes from '%s' to '%s':\n", $c->{fromstr}, $c->{tostr};
  } else {
    next;
  }
  for my $p ($c->solvables()) {
    if ($c->{type} == $solv::Transaction::SOLVER_TRANSACTION_UPGRADED || $c->{type} == $solv::Transaction::SOLVER_TRANSACTION_DOWNGRADED) {
      my $other = $trans->othersolvable($p);
      printf "  - %s -> %s\n", $p->str(), $other->str();
    } else {
      printf "  - %s\n", $p->str();
    }
  }
  print "\n";
}
printf "install size change: %d K\n\n", $trans->calc_installsizechange();

while (1) {
  print("OK to continue (y/n)? ");
  my $yn = <STDIN>;
  chomp $yn;
  last if $yn eq 'y';
  exit(1) if $yn eq 'n' || $yn eq 'q';
}

my @newpkgs = $trans->newsolvables();
my %newpkgsfps;
if (@newpkgs) {
  my $downloadsize = 0;
  $downloadsize += $_->lookup_num($solv::SOLVABLE_DOWNLOADSIZE) for @newpkgs;
  printf "Downloading %d packages, %d K\n", scalar(@newpkgs), $downloadsize / 1024;
  for my $p (@newpkgs) {
    my $repo = $p->{repo}->{appdata};
    my ($location) = $p->lookup_location();
    next unless $location;
    $location = $repo->packagespath() . $location;
    my $chksum = $p->lookup_checksum($solv::SOLVABLE_CHECKSUM);
    my $f = $repo->download($location, 0, $chksum);
    die("\n$repo->{alias}: $location not found in repository\n") unless $f;
    $newpkgsfps{$p->{id}} = $f;
    print ".";
    STDOUT->flush();
  }
  print "\n";
}

print "Committing transaction:\n\n";
$trans->order();
for my $p ($trans->steps()) {
  my $steptype = $trans->steptype($p, $solv::Transaction::SOLVER_TRANSACTION_RPM_ONLY);
  if ($steptype == $solv::Transaction::SOLVER_TRANSACTION_ERASE) {
    print "erase ".$p->str()."\n";
    next unless $p->lookup_num($solv::RPM_RPMDBID);
    my $evr = $p->{evr};
    $evr =~ s/^[0-9]+://;	# strip epoch
    system('rpm', '-e', '--nodeps', '--nodigest', '--nosignature', "$p->{name}-$evr.$p->{arch}") && die("rpm failed: $?\n");
  } elsif ($steptype == $solv::Transaction::SOLVER_TRANSACTION_INSTALL || $steptype == $solv::Transaction::SOLVER_TRANSACTION_MULTIINSTALL) {
    print "install ".$p->str()."\n";
    my $f = $newpkgsfps{$p->{id}};
    my $mode = $steptype == $solv::Transaction::SOLVER_TRANSACTION_INSTALL ? '-U' : '-i';
    $f->cloexec(0);
    system('rpm', $mode, '--force', '--nodeps', '--nodigest', '--nosignature', "/dev/fd/".$f->fileno()) && die("rpm failed: $?\n");
    delete $newpkgsfps{$p->{id}};
  }
}

exit 0;
